import { store } from '@/store/setup'
import { defineStore } from 'pinia'
import { bwUtilsCookie } from '@/utils'
import { onSetRefreshTokenTimeout } from './utils/token'

import { BwCacheEnum } from '@/enums/cacheEnum'

import type { BwStorageStateModel } from './model'
const useStorageStore = defineStore({
  id: 'BwStorageStore',
  state: (): BwStorageStateModel => ({
    token: null,
    curStorageInfo: {},
  }),
  getters: {
    getToken(): string {
      return this.token ?? bwUtilsCookie.getCookie(BwCacheEnum.token) ?? ''
    },

    /** 获取存储信息 */
    getStorageInfo(): Record<string, any> {
      let curInfo = this.curStorageInfo ?? null
      if (!curInfo) {
        const storageInfo = bwUtilsCookie.getCookie(BwCacheEnum.storage)
        if (storageInfo) {
          curInfo = JSON.parse(storageInfo)
        }
      }
      return curInfo
    },

    /** 获取存储键值 */
    getStorageValueToKey(): Function {
      let curInfo = this.curStorageInfo ?? null
      if (!curInfo) {
        const storageInfo = bwUtilsCookie.getCookie(BwCacheEnum.storage)
        if (storageInfo) {
          curInfo = JSON.parse(storageInfo)
        }
      }
      return (key: string, defaultValue?: any) => curInfo[key] ?? defaultValue
    },
  },
  actions: {
    setToken(token?: Nullable<string>) {
      this.token = token ? token : null

      bwUtilsCookie.setCookie(BwCacheEnum.token, token ?? '', { expires: 7 })
      onSetRefreshTokenTimeout()
    },

    /** 设置存储信息 */
    setStorageInfo(key: string, info: any) {
      let curInfo: any = bwUtilsCookie.getCookie(BwCacheEnum.storage)

      curInfo = curInfo ? JSON.parse(curInfo) ?? {} : {}
      curInfo[key] = info

      this.curStorageInfo = curInfo
      bwUtilsCookie.setCookie(BwCacheEnum.storage, JSON.stringify(curInfo), {
        expires: 7,
      })
    },

    /** 删除存储信息 */
    delStorageInfo() {
      this.curStorageInfo = {}
      bwUtilsCookie.delCookie(BwCacheEnum.storage)
    },
  },
})

export function useStorageStoreWithOut() {
  return useStorageStore(store)
}
